package com.yunhai.store.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunhai.common.dto.GlobalException;
import com.yunhai.common.dto.PaginationVo;
import com.yunhai.common.utils.ObjectUtil;
import com.yunhai.common.utils.ReflectionCopy;
import com.yunhai.model.entity.tms.TmsStoreCategoryEntity;
import com.yunhai.model.entity.tms.TmsStoreEntity;
import com.yunhai.model.entity.tms.TmsStoreGroupEntity;
import com.yunhai.model.vo.tms.TmsStoreGroupBatchAddVo;
import com.yunhai.model.vo.tms.TmsStoreQuery;
import com.yunhai.model.vo.tms.TmsStoreVo;
import com.yunhai.store.listener.TmsStoreGroupListener;
import com.yunhai.store.mapper.TmsStoreCategoryMapper;
import com.yunhai.store.mapper.TmsStoreGroupMapper;
import com.yunhai.store.mapper.TmsStoreMapper;
import com.yunhai.store.service.TmsStoreService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TmsStoreServiceImpl implements TmsStoreService {

    @Resource
    private TmsStoreMapper tmsStoreMapper;
    @Resource
    private TmsStoreCategoryMapper tmsStoreCategoryMapper;
    @Resource
    private TmsStoreGroupMapper tmsStoreGroupMapper;
    @Resource
    private FmsCodeDictServiceImpl fmsCodeDictService;
    /**
     * 获取 TmsStore 分页列表
     */
    @Transactional
    public IPage getTmsStorePagination(PaginationVo paginationVo, TmsStoreQuery tmsStoreQuery ) throws Exception {

        IPage page = new Page( paginationVo.getPageIndex(), paginationVo.getPageSize() );
        LambdaQueryWrapper<TmsStoreEntity> lqs = new LambdaQueryWrapper();
        if( tmsStoreQuery.getName() != null ){
            lqs.and(wrapper -> wrapper
                    .likeRight(TmsStoreEntity::getName, tmsStoreQuery.getName())
                    .or()
                    .likeRight(TmsStoreEntity::getShortName, tmsStoreQuery.getName())
            );
        }
        lqs.eq(tmsStoreQuery.getStoreGroupId() != null, TmsStoreEntity::getStoreGroupId, tmsStoreQuery.getStoreGroupId());
        lqs.eq(tmsStoreQuery.getStoreCategoryId() != null, TmsStoreEntity::getStoreCategoryId, tmsStoreQuery.getStoreCategoryId());
        lqs.eq(tmsStoreQuery.getEnabled() != null, TmsStoreEntity::getEnabled, tmsStoreQuery.getEnabled());
        lqs.eq(tmsStoreQuery.getIsClosed() != null, TmsStoreEntity::getIsClosed, tmsStoreQuery.getIsClosed());
        lqs.eq(tmsStoreQuery.getProvinceId() != null, TmsStoreEntity::getProvinceId, tmsStoreQuery.getProvinceId());
        lqs.eq(tmsStoreQuery.getCityId() != null, TmsStoreEntity::getCityId, tmsStoreQuery.getCityId());
        lqs.eq(tmsStoreQuery.getAreaId() != null, TmsStoreEntity::getAreaId, tmsStoreQuery.getAreaId());
        lqs.orderByDesc(TmsStoreEntity::getCreateTime);
        tmsStoreMapper.selectPage(page, lqs);

        List<TmsStoreEntity> record = page.getRecords();
        if( !ObjectUtil.isNotEmptyList(record)){
            return page;
        }
        return page;
    }


    /**
     * 获取 TmsStore 所有数据
     *
    */
    @Transactional
    public List<TmsStoreEntity> getTmsStoreAllList( TmsStoreQuery tmsStoreQuery ) throws Exception {

        LambdaQueryWrapper<TmsStoreEntity> lqs = new LambdaQueryWrapper();
        List<TmsStoreEntity> list = tmsStoreMapper.selectList(lqs);
        return list;
    }


    /**
     * 获取 TmsStore 详情
    */
    @Transactional
    public TmsStoreEntity getTmsStoreDetail( Long id) throws Exception {

        TmsStoreEntity tmsStore = tmsStoreMapper.selectById(id);
        return tmsStore;
    }


    /**
     * 新增 TmsStore
     * */
    @Transactional
    public void addTmsStore(TmsStoreVo tmsStoreVo) throws Exception {

        if( tmsStoreVo.getIsClosed() == null ){
            tmsStoreVo.setIsClosed(0);
        }
        if( tmsStoreVo.getName() == null ){
            tmsStoreVo.setName("暂无门店名");
        }

        TmsStoreEntity tmsStore = new TmsStoreEntity();
        ReflectionCopy.copyProperties( tmsStore, tmsStoreVo );

        //处理 storeCategoryName
        Long storeCategoryId = tmsStore.getStoreCategoryId();
        TmsStoreCategoryEntity tmsStoreCategoryEntity = tmsStoreCategoryMapper.selectById(storeCategoryId);
        if( tmsStoreCategoryEntity == null ){
            throw GlobalException.gen(11011, "分类不存在");
        }

        //处理 storeGroupName
        Long storeGroupId = tmsStore.getStoreGroupId();
        TmsStoreGroupEntity tmsStoreGroupEntity = tmsStoreGroupMapper.selectById(storeGroupId);
        if( tmsStoreGroupEntity == null ){
            throw GlobalException.gen(11012, "门店地区错误");
        }

        tmsStore.setStoreCategoryName(tmsStoreCategoryEntity.getName());
        tmsStore.setStoreGroupName(tmsStoreGroupEntity.getName());

        tmsStoreMapper.insert(tmsStore);
        fmsCodeDictService.updateById(9L, tmsStoreVo.getNumber());
        return;
    }


    @Override
    public void batchAddTmsStoreByExcelFile(MultipartFile file) throws Exception {
        TmsStoreGroupListener listener = new TmsStoreGroupListener();
        EasyExcel.read(file.getInputStream(), TmsStoreGroupBatchAddVo.class,listener).sheet().doRead();;
        List<TmsStoreGroupBatchAddVo> list = listener.getList();
        //去数据库中查找是否存在
        System.out.println("storeGroupList:"+list);

        //获取所有的区域
        Map<String, TmsStoreGroupEntity> map = new HashMap();
        List<TmsStoreGroupEntity> storeGroupListFromSql = tmsStoreGroupMapper.selectList(null);
        if( storeGroupListFromSql != null ){
            for(  TmsStoreGroupEntity item : storeGroupListFromSql ){
                map.put(item.getName(), item);
            }
        }

        Map<String, TmsStoreCategoryEntity> categoryMap = new HashMap();
        List<TmsStoreCategoryEntity> tmsStoreCategoryEntities = tmsStoreCategoryMapper.selectList(null);
        if( tmsStoreCategoryEntities != null ){
            for(  TmsStoreCategoryEntity item : tmsStoreCategoryEntities ){
                categoryMap.put(item.getName(), item);
            }
        }

//        List<TmsStoreVo> storeList = new ArrayList<>();
        for( TmsStoreGroupBatchAddVo item : list ){

            //设置门店组
            TmsStoreVo tmsStoreVo = new TmsStoreVo();

            //设置 number
            String number = fmsCodeDictService.getCanUseCode(9);
            tmsStoreVo.setNumber(number);
            //设置 name
            tmsStoreVo.setName( item.getStoreName() );

            //设置省市区
            tmsStoreVo.setProvinceName(item.getProvinceName());
            tmsStoreVo.setCityName(item.getCityName());
            tmsStoreVo.setAreaName(item.getAreaName());

            //设置主管
            tmsStoreVo.setManager(item.getManagerPersonName());
            //设置督导
            tmsStoreVo.setSupervision(item.getSupervisionPersonName());

            //设置门店分类
            TmsStoreCategoryEntity cacheCategoryItem = categoryMap.get(item.getStoreCategory());
            if( cacheCategoryItem != null ){
                tmsStoreVo.setStoreCategoryId(cacheCategoryItem.getId());
                tmsStoreVo.setStoreCategoryName(cacheCategoryItem.getName());
            }

            String regionName= item.getRegionName();
            String provinceName = item.getProvinceName();
            String cityName = item.getCityName();
            String areaName = item.getAreaName();

            //进行数量的统计
            TmsStoreGroupEntity groupItem = handleStoreAmountOfGroupItem(map,regionName, null);
            groupItem = handleStoreAmountOfGroupItem(map,provinceName,groupItem);
            groupItem = handleStoreAmountOfGroupItem(map,cityName,groupItem);
            groupItem = handleStoreAmountOfGroupItem(map,areaName,groupItem);
            //如果groupItem 不存在，则 parentId == 0

            //设置门店组
            if( groupItem == null ){
                tmsStoreVo.setStoreGroupId(null);
                tmsStoreVo.setStoreGroupName("");
            }else {
                tmsStoreVo.setStoreGroupId(groupItem.getId());
                tmsStoreVo.setStoreGroupName(groupItem.getName());
            }

            //营业状态
            //(0-管理中，1-已闭店，2-未开业)
            Integer openStatus = 0;
            switch ( item.getOpenStatus() ){
                case "管理中":
                    openStatus = 0;
                    break;
                case "已闭店":
                    openStatus = 1;
                    break;
                case "未开业":
                    openStatus = 2;
                    break;
            }
            tmsStoreVo.setEnabled(openStatus);

            //门店状态
            //(0-营业中，1-歇业中，2-已闭店，3-选址中， 4-筹建中， 5-已退单)
            Integer storeStatus = 0;
            if( item.getStoreStatus() ==  null ){
                item.setStoreStatus("");
            }
            switch ( item.getStoreStatus() ){
                case "营业中":
                    storeStatus = 0;
                    break;
                case "歇业中":
                    storeStatus = 1;
                    break;
                case "已闭店":
                    storeStatus = 2;
                    break;
                case "选址中":
                    storeStatus = 3;
                    break;
                case "筹建中":
                    storeStatus = 4;
                    break;
                case "已退单":
                    storeStatus = 5;
                    break;
            }
            tmsStoreVo.setIsClosed(storeStatus);

            tmsStoreVo.setFirstOpenDate(item.getFirstOpenDate());
            tmsStoreVo.setLastOpenDate(item.getLastOpenDate());
            tmsStoreVo.setCloseDate(item.getCloseDate());
            tmsStoreVo.setOutStoreId(item.getStoreId());
            tmsStoreVo.setOutStoreNumber(item.getStoreCode());
            this.addTmsStore(tmsStoreVo);
        }
  }

    @Override
    public List<TmsStoreVo> getTmsStoreByIds(List<Long> ids) throws Exception {
        List<TmsStoreEntity> tmsStoreEntities = tmsStoreMapper.selectBatchIds(ids);
        List<TmsStoreVo> list = new ArrayList<>();
        if( tmsStoreEntities == null ){
            return list;
        }

        list = tmsStoreEntities.stream().map( item->{
            TmsStoreVo tmsStoreVo = new TmsStoreVo();
            ReflectionCopy.copyProperties(tmsStoreVo, item);
            return tmsStoreVo;
        }).collect(Collectors.toList());
        return list;
    }


    private TmsStoreGroupEntity handleStoreAmountOfGroupItem(
            Map<String, TmsStoreGroupEntity> map ,
            String name,
            TmsStoreGroupEntity groupItem){

       TmsStoreGroupEntity groupItem1 = map.get(name);
       if( groupItem1 !=  null ){
           groupItem1.setStoreAmount( groupItem1.getStoreAmount()+1 );
           return groupItem1;
       }
       return groupItem;
   }

    /**
     * 更新 TmsStore
     * */
    @Transactional
    public void updateTmsStore( TmsStoreVo tmsStoreVo) throws Exception {

        if( tmsStoreVo.getId() == null ){
            throw GlobalException.gen(10021, "id不存在");
        }
        TmsStoreEntity tmsStore = new TmsStoreEntity();
        ReflectionCopy.copyProperties( tmsStore, tmsStoreVo );
        tmsStoreMapper.updateById(tmsStore);
        return;
    }

    /**
     * 删除 TmsStore
     * */
    @Transactional
    public void batchRemoveTmsStore( List<Long> ids ) throws Exception {


        if( !ObjectUtil.isNotEmptyList(ids) ){
            throw GlobalException.gen(10011, "要删除的id不存在");
        }
        tmsStoreMapper.deleteBatchIds(ids);
    }



}

      